<template>
	<view :data-theme="theme" class="container">
		<view class="card">
			<view class="header-top" style="position: relative;">
				<view class="header_name">【扶持】{{activeData.name}}</view>
				<view class="main_color" style="font-size: 30rpx;">活动中</view>
			</view>
			<view class="border-item">
				<view class="header-top" @click="activeIsShow" style="margin-top: 20rpx;line-height: 100rpx;">
					<view style="font-size: 33rpx;font-weight: bold;">商品要求</view>
					<u-icon :name="showUpClassPopup?'arrow-up':'arrow-down'" size="14"></u-icon>
				</view>
				<view v-if="showUpClassPopup"
					style="color: #080808;line-height: 1.3;font-size: 30rpx;padding-bottom: 30rpx;">
					{{activeData.datailContent}}
				</view>
			</view>
		</view>
		<view style="margin: 30rpx;display: flex;justify-content: space-between;">
			<view style="font-weight: bold;font-size: 33rpx;">
				可参与活动的商品
			</view>
			<!-- <view class="main_color" style="font-size: 33rpx;" @click="batchSetup">
				<span>{{this.isShowCheckbox?'取消':'批量设置'}}</span>
			</view> -->
		</view>

		<!-- 商品列表 -->
		<scroll-view scroll-y="true" :style="{ 'margin-bottom':'140rpx' }" style="height: 100%; overflow: hidden;">
			<set-seckill-page :bgColor="bgColor" ref="tab" :productData.sync="productData"
				:activeDateTime="activeDateTime" :isShowCheckbox="isShowCheckbox" @update-item="updateItem"
				@submitRegist="submitRegistration" @isAllChecked="isAllCheck" @updateProduct="updateProduct"
				@checkboxChange="checkboxChange" :key="uniqueKey"></set-seckill-page>
		</scroll-view>

		<view class="footer" v-if="!isShowCheckbox"
			style="position: fixed;bottom: 0px;width: 100%;padding: 10px;background-color: #FFF;align-items: center;">
			<view style="display: flex;align-items: center;">
				<button :color="bgColor" :loading="loading"
					style="font-weight: bold;border-radius: 10px;color: #000;padding: 20rpx;flex: 1;margin: 0 10rpx;background-color: #f2f2f2;"
					@click="goBackConsign()">上一步,选择商品</button>
				<button :color="bgColor" class="bg_color"
					style="font-weight: bold;border-radius: 10px;color: #FFF;padding: 20rpx;flex: 1;margin: 0 10rpx;"
					@click="submitForm()">提交报名</button>
			</view>
		</view>

		<!-- <view class="footer" v-if="isShowCheckbox"
			style="position: fixed;bottom: 0px;width: 100%;padding: 10px;background-color: #FFF;align-items: center;">
			<view class="checkAll" style="display: flex;margin: 14rpx 0;">
				<checkbox-group @change="allSelectChange" style="flex: 1;">
					<label class="uni-list-cell uni-list-cell-pd" style="display: flex;line-height: 34rpx;">
						<view>
							<checkbox :value="isAllChecked.toString()" :checked="isAllChecked" />
						</view>
						<view>全选</view>
					</label>
				</checkbox-group>
				<span>已选择{{checkboxValue.length}}个商品</span>
			</view>
			<view style="display: flex;align-items: center;">
				<button
					style="font-weight: bold;border-radius: 10px;color: #000;padding: 20rpx;flex: 1;margin: 0 10rpx;background-color: #f2f2f2;"
					@click="batchRemove()">删除</button>
				<button :color="bgColor" class="bg_color"
					style="font-weight: bold;border-radius: 10px;color: #FFF;padding: 20rpx;flex: 1;margin: 0 10rpx;"
					@click="msetKeyValue()">设置库存及限购数量</button>
			</view>
		</view> -->

	</view>
</template>

<script>
	import {
		addSeckillProApi
	} from "@/api/marketing.js";
	// import addedActiveGoods from "../components/added-active-goods.vue";
	// import tuiDrawer from '../components/tui-drawer/index.vue';
	import setSeckillPage from '../components/set-seckill-page.vue';
	import {
		setThemeColor
	} from '@/utils/setTheme.js';
	let app = getApp();
	export default {
		components: {
			setSeckillPage,
			// 	tuiDrawer
		},
		data() {
			return {
				bgColor: "#ffffff",
				theme: app.globalData.theme,
				productAttrParam: '',
				productData: [],
				activeDateTime: "",
				showUpClassPopup: false,
				activeData: {
					oldPrice: 13.92, //原价
					image: 'http://192.168.1.29:28080/img_xyt/public/product/2024/04/23/3669c2389d38458582e36ee84d6fe235o80gc46lgn.png',
					brandName: '绿色和美',
					name: "鸭血 6kg/箱(20盒)",
					status: 1, //活动状态
					datailContent: "提报价格需低于招商指导价，相同商品取提报活动价低品优先展示，给出价格力度越高，提报成功率越高。",
					endTime: "2024.4.30 23:59:59",
					activeTime: "2024.04.17-2024.04.30",
					queryStatus: 1, //1直接生效
					requirements: '冻品尝鲜价专栏(冻肉、速食熟食、冷冻半成品、调理包)，限商品新客可享尝鲜价优惠价格，通过商城流量及首页固定栏目位高效转化新客!',
				},
				totalInventory: null, //尝鲜促销价
				newPrice: null,
				showNewTop: false,
				//-------------------
				isAllChecked: false,
				isShowCheckbox: false, //批量设置
				// ---------弹窗------------
				showGroupCategory: false,
				// ------促销总库存模式--------
				skuArr2: [{
					name: "不限",
					type: '-1'
				}, {
					name: "自定义",
					type: '2'
				}],
				invoteKeyValue: {
					totalInventoryModel: '-1', //促销总库存
					promotionInventory: 1, //促销总库存初始值1
					daylimitModel: '-1', //单日限购状态
					customerTotalLimit: 1, //单日限购初始值1
					totalRestriction: '-1', //单客户总限购
					customerTotalLimit: 1, //单客户总限购初始值1
					showTotalInventory: false, //促销总库存自定义
					//-------------------------------------
					showDayLimitModel: false, //客户单日限购自定义
					//-------------------------------------
					showtotalRestriction: false, //客户总限购自定义
				},

				//------------------
				allSelect: [0],
				uniqueKey: 0,
				activityId: '',
				loading: false,
				checkboxValue: [],
				form:{
					id:0,
				},
			};
		},
		onLoad(options) {
			this.bgColor = setThemeColor();
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: this.bgColor,
			});

			let that = this;
			this.activityId = options.activityId;

			// APP-NVUE平台暂不支持以this.getOpenerEventChannel()方式获取eventChannel，请换用this.$scope.eventChannel来获取
			// #ifdef APP-NVUE
			const eventChannel = this.$scope.eventChannel; // 兼容APP-NVUE
			// #endif
			// #ifndef APP-NVUE
			const eventChannel = this.getOpenerEventChannel();
			// #endif
			// 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
			eventChannel.on('productAttr', function(param) {
				that.productAttrParam = param;
				console.log(param)
				that.productData = param.data;
				that.activeDateTime = param.activeDateTime;
			});
		},
		methods: {
			activeIsShow() {
				this.showUpClassPopup = !this.showUpClassPopup;
			},
			updateItem(updatedItem, index) {
				// 根据子组件传递的更新后的项更新父组件中的数组对象
				this.productData[index] = updatedItem
			},
			
			goPage(url, success) {
				uni.navigateTo({
					url,
					success: success
				})
			},

			// 批量设置
			batchSetup() {
				this.isShowCheckbox = !this.isShowCheckbox;
			},

			// 返回上一级，选择商品
			goBackConsign() {
				let pages = getCurrentPages() // 获取当前页面栈的实例，以数组形式按栈的顺序给出，第一个元素为首页，最后一个元素为当前页面。
				let prevPage = pages[pages.length - 2] //上一页页面实例
				uni.navigateBack({
					delta: 1,
					// success: () => {
					// 	prevPage.$vm.otherFun(param) // 给上一页绑定方法otherFun,
					// }
				})
			},

			//库存，限购模式，类型；批量设置选择事件
			tapAttr2(ele, sign) {
				switch (sign) {
					case '1': //促销总库存
						this.$set(this.invoteKeyValue, 'totalInventoryModel', ele.type) //1不限，2自定义
						this.$set(this.invoteKeyValue, 'promotionInventory', 1);

						if (ele.type == '2') {
							this.$set(this.invoteKeyValue, 'showTotalInventory', true)
						} else {
							this.$set(this.invoteKeyValue, 'showTotalInventory', false)
						}
						break;
					case '2': //单客户单日限购
						this.$set(this.invoteKeyValue, 'daylimitModel', ele.type) //1不限，2自定义
						this.$set(this.invoteKeyValue, 'customerTotalLimit', 1); //初始值
						if (ele.type == '2') {
							this.$set(this.invoteKeyValue, 'showDayLimitModel', true)
						} else {
							this.$set(this.invoteKeyValue, 'showDayLimitModel', false)
						}
						break;
					case '3': //单客户总限购
						this.$set(this.invoteKeyValue, 'totalRestriction', ele.type) //1不限，2自定义
						this.$set(this.invoteKeyValue, 'customerTotalLimit', 1); //初始值
						if (ele.type == '2') {
							this.$set(this.invoteKeyValue, 'showtotalRestriction', true)
						} else {
							this.$set(this.invoteKeyValue, 'showtotalRestriction', false)
						}
						break;
				}
			},
			// ----促销总库存----
			blur2(res) {
				if (res.value == "") {
					this.promotionInventory = 1;
				}
			},

			//-----弹窗确认事件----
			/** 
			 *批量设置值
			 */
			msetKeyValue() {
				let that = this;
				console.log(this.checkboxValue);
				that.showGroupCategory = true;
			},
			/** 
			确认事件
			 */
			confirmReceipt() {
				console.log('this.invoteKeyValue', this.invoteKeyValue);
				let that = this;
				this.checkboxValue.forEach(element => {
					// 找到b数组中匹配的对象
					let matchedObject = this.productData.find(obj => obj.id === element);
					if (matchedObject) {
						matchedObject.totalInventoryModel = this.invoteKeyValue.totalInventoryModel; //促销总库存
						matchedObject.promotionInventory = this.invoteKeyValue.promotionInventory; //促销总库存初始值1
						matchedObject.daylimitModel = this.invoteKeyValue.daylimitModel; //单日限购状态

						matchedObject.customerTotalLimit = this.invoteKeyValue.customerTotalLimit; //单日限购初始值1
						matchedObject.totalRestriction = this.invoteKeyValue.totalRestriction; //单客户总限购
						matchedObject.customerTotalLimit = this.invoteKeyValue.customerTotalLimit; //单客户总限购初始值1

						matchedObject.showTotalInventory = this.invoteKeyValue.showTotalInventory; //促销总库存自定义
						//-------------------------------------
						matchedObject.showDayLimitModel = this.invoteKeyValue.showDayLimitModel; //客户单日限购自定义
						//-------------------------------------
						matchedObject.showtotalRestriction = this.invoteKeyValue.showtotalRestriction; //客户总限购自定义
					}
				});
				const newProductDate = this.productData;
				let page = this.$refs.tab;

				page.updateProduct(newProductDate);
				that.showGroupCategory = false;
				that.isShowCheckbox = false;
				that.uniqueKey += 1; // 改变 key 值强制重新渲染子组件
			},
			isAllCheck(value) {
				this.isAllChecked = value;
			},
			//多选
			checkboxChange(checkboxValue) {
				this.checkboxValue = checkboxValue;
				this.updateAllSelectState();
			},
			//更新全选按钮状态
			updateAllSelectState(index) {
				let i = index == null ? this.currentIndex : index;
				if (this.checkboxValue.length > 0) {
					this.allSelect = [1];
				} else {
					this.isAllChecked = false;
					this.allSelect = [];
				}
			},
			//多选按钮事件
			allSelectChange(checkboxValue) {
				let page = this.$refs.tab;
				if (checkboxValue.detail.value.length > 0) {
					page.checkboxAllSelect();
				} else {
					page.checkboxAllSelect(true);
				}
			},

			//-----------------------------
			/** 
			关闭事件
			 */
			close() {
				this.showGroupCategory = false;
				this.invoteKeyValue = {
					totalInventoryModel: '-1', //促销总库存
					promotionInventory: 1, //促销总库存初始值1
					daylimitModel: '-1', //单日限购状态
					customerTotalLimit: 1, //单日限购初始值1
					totalRestriction: '-1', //单客户总限购
					totalRestrictionNum: 1, //单客户总限购初始值1
					showTotalInventory: false, //促销总库存自定义
					//-------------------------------------
					showDayLimitModel: false, //客户单日限购自定义
					//-------------------------------------
					showtotalRestriction: false, //客户总限购自定义
				};
			},
			/* 
			 *批量删除*/
			batchRemove() {
				const idsToRemove = this.productData.filter(item => !this.checkboxValue.includes(item.id));

				this.productData = idsToRemove;
				this.isShowCheckbox = false;
			},

			/** 确认 */
			submitForm() {
				console.log(this.productData)
                for (let ele of this.productData) {
                	if (ele.activityPrice == '' || !ele.activityPrice) {
                		uni.showToast({
                			title: "请先设置商品价格",
                			icon: "none",
                		})
                		return
                	};
					if (ele.quota == '0' || !ele.quota) {
						uni.showToast({
							title: "库存应当大于0",
							icon: "none",
						})
						return
					}
                }

				let newDataValue = this.productData.reduce((acc, obj) => {
					const isInreduce = acc.find(item => item.id === obj.parentId);
					if (isInreduce) {
						isInreduce.attrValue.push({
							activityPrice: obj.activityPrice,
							attrValueId: obj.skuId,
							operateCityId: obj.operateCityId,
							quota: obj.quota,
						});
					} else {
						acc.push({
							sort: obj.sort,
							id: obj.parentId,
							attrValue: [{
								activityPrice: obj.activityPrice,
								attrValueId: obj.skuId,
								operateCityId: obj.operateCityId,
								quota: obj.quota,
							}]
						});
					}
					return acc;
				}, [])
				console.log('newDataValue:', newDataValue)
				
				
				// let list = this.proData;
				// //this.auditStatus === 3 获取商品规格id。因为重新提交 相当于添加商品，取普通商品规格id
				// if (this.auditStatus === 3) {
				// 	this.form.productList = list.map((item) => {
				// 		return {
				// 			id: this.productId,
				// 			sort: item.sort,
				// 			attrValue: item.attrValue.map((item1, idx) => {
				// 				return {
				// 					activityPrice: item1.activityPrice,
				// 					attrValueId: this.attrValue[idx].skuId,
				// 					quota: item1.quota,
				// 					operateCityId: item1.operateCityId,
				// 				};
				// 			}),
				// 		};
				// 	});
				// } else {
				// 	this.form.productList = list.map((item) => {
				// 		return {
				// 			id: item.id,
				// 			sort: item.sort,
				// 			attrValue: item.attrValue.map((item1) => {
				// 				return {
				// 					activityPrice: item1.activityPrice,
				// 					attrValueId: item1.skuId,
				// 					quota: item1.quota,
				// 					operateCityId: item1.operateCityId,
				// 				};
				// 			}),
				// 		};
				// 	});
				// }
				this.form.id = this.activityId ? this.activityId : this.form.id;
				this.form.productList = newDataValue;
				addSeckillProApi(this.form)
					.then((res) => {
						uni.showToast({
							title: "提交成功，请前往配置库存",
							icon: "success",
						});
						// if (this.$route.params.activityId) {
						// 	this.$router.push({
						// 		path: `/marketing/seckill/seckillActivity`
						// 	});
						// } else {
						// 	this.$router.push({
						// 		path: `/marketing/seckill/list`
						// 	});
						// }
					})
					.catch((res) => {
						console.log('res:',res)
					});

			},
		}
	}
</script>

<style lang="scss">
	.container {
		display: flex;
		flex-direction: column;
		height: 100%;
	}

	// // #ifndef APP-PLUS */
	// page {
	// 	width: 100%;
	// 	min-height: 100%;
	// 	// display: flex;
	// }

	// /* #endif

	page {
		height: 100%;
	}

	.container {
		display: flex;
		flex-direction: column;
		height: 100%;
	}

	.bg_color {
		@include main_bg_color(theme);
	}

	.main_color {
		@include main_color(theme);
	}

	.plain_bgColor {
		@include main_color(theme);
		@include main_bg_rgba_color(theme, 0.05);
		// border: 1rpx solid $main-color-theme1;
		border: 1rpx solid;
	}

	.card {
		margin: 20rpx;
		background-color: #fff;
		border-radius: 20rpx;
		padding: 20rpx;
	}

	.header-top {
		display: flex;
		justify-content: space-between;
	}

	.product_demo {
		display: flex;
	}

	.header_name {
		font-size: 31rpx;
		font-weight: bolder;
	}

	// .border-item {
	// 	border-bottom: 1px solid #f3f3f3;
	// }

	.swiper-item {
		flex: 1;
		flex-direction: column;
	}

	.swiper-page {
		flex: 1;
		flex-direction: column;
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
	}

	.tab-view {
		display: flex;
		flex-direction: column;
		flex: 1;
		height: 820rpx;

		.scroll-view {
			height: 100%;
		}
	}

	.sku-select1 {
		.flex-text {
			margin: 8rpx 8rpx;
			background-color: #fff;
			line-height: 62rpx;
			text-align: center;
			color: #777;
			padding: 0 24rpx;
			font-size: 28rpx;
			border-radius: 12rpx;
			border: 2rpx solid #dddddd;
		}

		.right-class-active {
			@include main_color(theme);
			// @include main_bg_rgba_color(theme, 0.05);
			border: 2rpx solid;
		}
	}

	.ensure {
		width: 100%;
		background-color: #fff;
		padding-bottom: 22rpx;
		padding-bottom: calc(22rpx+ constant(safe-area-inset-bottom)); ///兼容 IOS<11.2/
		padding-bottom: calc(22rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/

		.title {
			font-size: 36rpx;
			color: #282828;
			text-align: center;
			margin: 38rpx 0 36rpx 0;
			position: relative;

			.iconfont {
				position: absolute;
				right: 30rpx;
				top: 0;
				font-size: 36rpx;
			}

			.iconfontRight {
				position: absolute;
				right: 30rpx;
				top: 0;
				font-size: 30rpx;
				@include main_color(theme);
			}
		}

		.titleRight {
			font-size: 30rpx;
			font-weight: bold;
			color: #282828;
			text-align: center;
			margin: 20rpx 10rpx 36rpx 0;
			position: relative;
			padding-bottom: 30rpx;
			border-bottom: 2rpx solid #f0edf0;

			.iconfont {
				position: absolute;
				right: 0;
				top: 0;
				font-size: 30rpx;
			}
		}
	}
</style>